package com.min.spring.service.impl;

import com.min.spring.service.MysqlInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

@Service
public class MysqlInfoServiceImpl implements MysqlInfoService {

    @Autowired
    DataSource dataSource;

    /**
     * show variables
     *
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, String> getVariables() {
        String sql = "show variables";
        return getMysqlInfoMap(sql);
    }

    @Override
    public Map<String, String> getStatus() {
        String sql = "show STATUS";
        return getMysqlInfoMap(sql);
    }


    /**
     * 获得数据库的一些相关信息
     */
    public void getDataBaseInformations() {
        DatabaseMetaData dbMetaData;
        try {
            //获取连接元数据DatabaseMetaData
            dbMetaData = dataSource.getConnection().getMetaData();

            System.out.println("数据库URL: " + dbMetaData.getURL());
            System.out.println("是否允许只读:" + dbMetaData.isReadOnly());
            System.out.println("数据库的产品名称:" + dbMetaData.getDatabaseProductName());
            System.out.println("数据库的版本:" + dbMetaData.getDatabaseProductVersion());
            System.out.println("驱动程序的名称:" + dbMetaData.getDriverName());
            System.out.println("驱动程序的版本:" + dbMetaData.getDriverVersion());
            System.out.println("最大行数:" + dbMetaData.getMaxRowSize());

            System.out.println();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private Map<String, String> getMysqlInfoMap(String sql) {
        Map<String, String> map = new HashMap<>();

        try {
            Statement state = dataSource.getConnection().createStatement();

            ResultSet rs = state.executeQuery(sql);
            while (rs.next()) {
                map.put(rs.getString(1), rs.getString(2));
            }

            rs.close();
            state.close();
        } catch (SQLException e) {
            return null;
        }
        return map;
    }
}
